Embedded Python API Reference

This chapter provides information on eCognition's embedded Python API with reference for each class, properties, and methods and gives serveral hints on printing and the usage of external python files in inline scripts. The embedded python API is accessible only from within the rule set algorithm 'python script' and is accessible by importing the eCognition package in python script.

Note - An external eCognition API is provided as python wheel package accessible from python program by installing the ecognitionapi package using the appropriate wheel package. See User Guide > Python Package Documentation .

Exemplary python scripts can be found in User Guide > Python Integration.

How to set up and use an external debugger for python files see User Guide > Python Integration > Debugging python code in eCognition Developer

Following successful first step in Python Integration in eCognition 10.3, we move forward and offer more capabilities that will enable seamless fusion of eCognition rule set and python scripts.

Python Classes, Functions and Methods

To define and call a Python function, the term parameter and argument is used to pass information to the function.

Input - input_dict

Exemplary Function Argument Structure

Copy
{
    "scene_info": {
        "LLX": float,
        "LLY": float,
        "resolution": float,
        "projection_string": str,
        "unit": str
    },
    "raster": {
        "name1": ecognition.Raster,
        "name2": ecognition.Raster,
        ...
    },
    "vector": {
        "name1": ecognition.Vector,
        "name2": ecognition.Vector,
        ...
    },
    "point_cloud": {
        "name1": ecognition.PointCloud,
        "name2": ecognition.PointCloud,
        ...
    },
    "variable" : {
        "name1": str | float,
        "name2": str | float,
        ...
    },
    "region" : {
        "name1": numpy.ndarray (check set_region function for region explanation),
        "name2": numpy.ndarray (check set_region function for region explanation),
        ...
    },
    "array" : {
        "name1": list[str | float],
        "name2": list[str | float],
        ...
    }
}

Here “name*” is equal to the name of the selected variable or layer in the 'execute python script' algorithm.

input_dict

This section describes the input for the embedded Python on creation of the 'python script' algorithm. The input parameters are passed to the python script via a data structure called dictionary (name-value pairs). The default name of the dictionary is input_dict and it can contain the following values:

"scene_info"

Dictionary containing keys:

"LLX": float

"LLY": float

"urx": float
"ury": float

"size_x": float
"size_y": float

"pixel_size": float
"resolution": float

"projection_string": str

"unit": str

 

scene_LLX = input_dict["scene_info"]["LLX"]
Example how to access scene information.

"raster"

Dictionary of ecognition.Raster class objects.

my_raster = input_dict["raster"]["Layer 1"]
Example how to access a raster layer.

"vector"

Dictionary of ecognition.Vector class objects.

my_vector = input_dict["vector"]["Thematic Layer 1"]
Example how to access a vector layer.

"point_cloud"

Dictionary of ecognition.PointCloud class objects.

my_pc = input_dict["point_cloud"]["Lidar"]
Example how to access a point cloud layer.

"variable"

Dictionary of variables of str or float type.

scene_size = input_dict["variable"]["var_scene_size"]
Example how to access a variable.

"region"

Dictionary of numpy.ndarray type.

region1 = input_dict["region"]["region1"]
Example how to access a region.

"array"

Dictionary of lists of str or float type.

arr1 = input_dict["array"]["arr1"]
Example how to access an array.

"feature"

Dictionary of ecognition.Feature class objects.

number_of_pixels = input_dict["feature"]["Number of pixels"]
Example how to access a feature.

 

The following chapters explain available methods, parameters, and returns for classes and functions.

Class Raster

Methods

read_data(x=0, y=0, sx=0, sy=0)

Reads data from the raster image object. Can be called multiple times, to allow reading data in chunks for large rasters.

Parameters:

x: int X data read starting location.
y: int Y data read starting location.
sx: int X data read size. If sx is equal to 0, then full size is read.
sy: int Y data read size. If sy is equal to 0, then full size is read.

Returns:

data: numpy.ndarray The read data in the shape of [sy, sx].

Raises:

ValueError If any of the arguments is negative, or either of x and y are bigger than scene size.

write_data(data, x_offset=0, y_offset=0)

Writes data to the raster image object. Can be called multiple times, to allow writing data in chunks for large rasters.

Parameters:

data: numpy.ndarray
The data to write into the raster. Must be of the same data type as a raster object. Must be a 2D Y-major array (y, x).

x_offset: int X data write starting location.

y_offset: int Y data write starting location.

Raises:

ValueError
If Raster is already closed, data type is mismatched, or out of bounds.

size()

Returns the size of the raster image.

Returns:

raster_size: tuple Tuple with 2 dimensions in format: (y_size, x_size).

get_datatype()

Returns the data type of the raster image.

Returns:

raster_datatype: numpy.dtype Data of the raster image as numpy dtype.

close()

Finalizes raster object. Must be called for new raster objects created with ecognition.Raster.create_raster method.

Raises:

ValueError When closing an already closed raster.

Static methods

create_raster(name, type)

Static method - Creates an empty raster with the given name and type. If the raster with the specified name already exists, it is deleted, before a new one is created.

Parameters:

name: str Name of the raster.

type: numpy.dtype Data type of the raster values.

Returns:

raster: ecognition.Raster The created raster.

Raises:

ValueError If type is unsupported.

create_raster(name, data)

Static method - Creates a raster from the given data, with the given name. Data type is the same as data.dtype. If the raster with the specified name already exists, it is deleted, before a new one is created.

Parameters:

name: str Name of the raster.

data: numpy.ndarray Data to fill the raster with.

Returns:

raster: ecognition.Raster The created raster.

Raises:

ValueError If type is unsupported, or out of bounds.

Warning - Note that the Y coordinate for regions was not used correctly in Raster.write_data and in Raster.read_data methods. It was interpreted as top-left corner of the data block, which is different to regions and eCognitions coordinate system, where Y starts at the bottom-left corner. This is fixed since eCognition Version 10.4.0: x/y in Raster.read_data and Raster.write_data methods now interpret Y as bottom coordinate of the data block. Now code like this runs correctly:

Copy
region= input_dict["region"]["myRegion"]
    data = layer.read_data(int(searchreg[0][0]), int(searchreg[0][1]),
    int(searchreg[1][0]), int(searchreg[1][1]))
    layer.write_data( data.astype("f"), int(searchreg[0][0]), int(searchreg[0][1]) )

 

Copy
class Raster:    
    def read_data(self, x: int = 0 , y: int = 0, sx: int = 0, sy: int = 0) -> numpy.ndarray: ...    
    def write_data(self, data: numpy.ndarray, x_offset: int = 0, y_offset: int = 0) -> None: ...    
    def size(self) -> Tuple[int, int]: ...    
    def get_datatype(self) -> numpy.dtype: ...    
    def close(self) -> None: ...    
    @overload    
    @staticmethod    
    def create_raster(name: str, type: numpy.dtype) -> Raster: ...    
    @overload    
    @staticmethod    
    def create_raster(name: str, data: numpy.ndarray) -> Raster: ...

Class Vector

Methods

get_geometry_type()

Returns the type of the vector geometry.

Returns:

geometry_type: str The string indicating geometry type.
Can be one of [“Point”, “Line”, “Polygon”, “Point3D”, “Line3D”, “Polygon3D”].

get_data()

Returns data of the vector as a pandas DataFrame. Geometries are located in the “geometry” column. Other attributes are contained in other columns. Geometries are objects from the shapely.geometry module.

Returns:

vector_data: pandas.DataFrame Vector data as pandas DataFrame.

close()

Finalizes the vector object. Must be called for new vector objects created with ecognition.Vector.create_vector method.

Static methods

create_vector(name, geometry_type, data)

Static method - Creates a vector from the given data, with the given name. If the vector with the specified name already exists, it is deleted, before a new one is created. pandas DataFrame given in the data argument must contain a “geometry” column, with at least one geometry. The elements of each DataFrame column must have the same type.

Parameters:

name: str Name of the vector.

geometry_type: str Type of the geometries. Must be one of [“Point”, “Line”, “Polygon”, “Point3D”, “Line3D”, “Polygon3D”]

data: pandas.DataFrame The data to fill the vector with.

Returns:

vector: ecognition.Vector The created vector.

Raises:

ValueError

If the geometry type is unsupported, pandas DataFrame does not contain a geometry column or is empty.

If the name is empty.

If attribute type is unsupported, or attribute elements are not of the same type.

 

Copy
class Vector:    
    def get_geometry_type(self) -> Literal["Point", "Line", "Polygon", "Point3D", "Line3D", "Polygon3D"]: ...    
    def get_data(self) -> pandas.DataFrame: ...    
    def close(self) -> None: ...    
    @staticmethod    
    def create_vector(name: str, geometry_type: Literal["Point", "Line", "Polygon", "Point3D", "Line3D", "Polygon3D"],                      
    data: pandas.DataFrame) -> Vector: ...    

Class PointCloudChunk

Attributes

x

Read-only property - Returns a numpy array of x coordinate values.

Returns:

x: numpy.ndarray The values of x coordinate.

y

Read-only property - Returns a numpy array of y coordinate values.

Returns:

y: numpy.ndarray The values of y coordinate.

z

Read-only property - Returns a numpy array of z coordinate values.

Returns:

z: numpy.ndarray The values of z coordinate.

intensity

Read-only property - Returns a numpy array of intensity values.

Returns:

intensity: numpy.ndarray The values of intensity.

red

Read-only property - Returns a numpy array of red values.

Returns:

red: numpy.ndarray The values of red.

green

Read-only property - Returns a numpy array of green values.

Returns:

green: numpy.ndarray The values of green.

blue

Read-only property - Returns a numpy array of blue values.

Returns:

blue: numpy.ndarray

The values of blue.

classification

Read-only property - Returns a numpy array of classification values.

Returns:

classification: numpy.ndarray The values of classification.

Special methods

__len__()

Returns the number of points in the chunk.

Returns:

length: int The number of points.

__repr__()

Returns the string representation of the chunk.

Returns:

repr: str String representation.

 

Copy
class PointCloudChunk:    
    @property    
    def x(self) -> numpy.ndarray: ...    
    @property    
    def y(self) -> numpy.ndarray: ...    
    @property    
    def z(self) -> numpy.ndarray: ...    
    @property    
    def intensity(self) -> numpy.ndarray: ...    
    @property    
    def red(self) -> numpy.ndarray: ...    
    @property    
    def green(self) -> numpy.ndarray: ...    
    @property    
    def blue(self) -> numpy.ndarray: ...    
    @property    
    def classification(self) -> numpy.ndarray: ...
    def __len__(self) -> int: ...    
    def __repr__(self) -> str: ...

Class PointCloudChunkIterator

Special methods

__iter__()

Returns self.

Returns:

self: ecognition.PointCloudChunkIterator Returns self.

__next__()

Returns the next point cloud chunk.

Returns:

chunk: ecognition.PointCloudChunk The point cloud chunk.

Copy
class PointCloudChunkIterator:    
    def __iter__(self) -> PointCloudChunkIterator: ...    
    def __next__(self) -> PointCloudChunk: ...

Class PointCloud

Methods

get_chunk_iterator(points_in_chunk=1000000)

Creates a chunk iterator, capable of iterating over the point cloud points. Only one PointCloudChunkIterator may exist at one time.

Parameters:

points_in_chunk: int
The number of points in a point cloud chunk.

Returns:

chunk_iterator: ecognition.PointCloudChunkIterator
The point cloud chunk iterator.

Raises:

ValueError
If point cloud is not closed, or an instance of PointCloudChunkIterator already exists.

add_points(x, y, z, intensity, red, green, blue, classification)

Adds point cloud points to the PointCloud object. Each field array must have the same size. Values of the same index correspond to the same point.

Parameters:

x: numpy.ndarray Numpy array containing point cloud x coordinates.

y: numpy.ndarray Numpy array containing point cloud y coordinates.

z: numpy.ndarray Numpy array containing point cloud z coordinates.

intensity: numpy.ndarray Numpy array containing point cloud intensity values.

red: numpy.ndarray Numpy array containing point cloud red values.

green: numpy.ndarray Numpy array containing point cloud green values.

blue: numpy.ndarray Numpy array containing point cloud blue values.

classification: numpy.ndarray Numpy array containing point cloud classification.

Raises:

ValueError
If closed.
If arguments have an unsupported data type, the number of dimensions is not equal to 1, or arguments element count is not equal.

get_point_count()

Returns the number of points in the PointCloud.

Returns:

point_count: int The number of points.

close()

Finalizes PointCloud object. Must be called for new PointCloud objects created with ecognition.PointCloud.create_point_cloud method.

Raises:

ValueError
If the point cloud is already closed.

Static Methods

create_point_cloud(name)

Static method - Creates an empty point cloud, with the given name. If the point cloud with the specified name already exists, it is deleted, before a new one is created.

Parameters:

name: str Name of the point cloud.

Returns:

point_cloud: ecognition.PointCloud The created point cloud.

Copy
class PointCloud:    
    def get_chunk_iterator(self, points_in_chunk: int = 1000000) -> PointCloudChunkIterator: ...    
    def add_points(self, x: numpy.ndarray, y: numpy.ndarray, z: numpy.ndarray, intensity: numpy.ndarray,                   
    red: numpy.ndarray, green: numpy.ndarray, blue: numpy.ndarray, classification: numpy.ndarray) -> None: ...    
    def get_point_count(self) -> int: ...    
    def close(self) -> None: ...    
    @staticmethod    
    def create_point_cloud(name: str) -> PointCloud: ...

Class ImageObject

Methods

get_pixel_count()

Returns number of pixels (area) of the image object.

Returns:

pixel_count: int The number of pixels.

get_classification()

Returns the class name with the best membership.

Returns:

class_name: str The name of the class.

set_classification(class_name, membership)

Sets classification result to 'membership' for class_name. Any other information is deleted.

Parameters:

class_name: str The name of the class.

membership: float The membership value for the class.

Raises:

RuntimeError
If the class does not exist or it cannot be created. 

get_border_length()

Returns length of the image object border in pixels.

Returns:

pixel_count: int The length of the border in pixels.

get_inner_pixel()

Returns the pixel which is inside the image object.

Returns:

inner_pixel: tuple Tuple with 2 dimensions in format: (x_coordinate, y_coordinate).

get_bounding_box()

Returns the bounding box of the image object.

Returns:

bounding_box: tuple Tuple with 4 dimensions in format: (min_x, min_y, size_x, size_y).

get_neighbours()

Returns a list of the neighbors of the image object.

Returns:

neighbors: list A list of ImageObject objects that have a common border with the current image object.

get_mask()

Returns the mask of the image object as a matrix of boolean pixel values.

Returns:

mask: numpy.ndarray The mask of the image object. It’s a 2D Y-major array (size_y, size_x).

__repr__()

Returns the string representation of the image object.

Returns:

repr: str String representation.


__str__()

Returns the string representation of the image object.

Returns:

str: str String representation.

Copy
class ImageObject:    
    def get_pixel_count(self) -> int: ...    
    def get_classification(self) -> str: ...    
    def set_classification(self, classification: str, membership: float) -> None: ...    
    def get_bounding_box(self) -> tuple[int, int, int, int]: ...    
    def get_inner_pixel(self) -> tuple[int, int]: ...    
    def get_mask(self) -> numpy.ndarray: ...    
    def get_neighbours(self) -> list[ImageObject]: ...

Class ProcessContext

Static Method

get_image_object_iterator()

Creates an image object iterator, capable of iterating over the image objects.

Returns:

iter: ImageObjectIterator
The iterator for ecognition.ImageObject.

Copy
class ProcessContext:    
    @staticmethod    
    def get_image_object_iterator() -> ImageObjectIterator: ...
    def set_variable(name: str, value: int | float | str) -> None: ...
    def set_array(name: str, values: Sequence[int | float | str]) -> None: ...
    def set_region(name: str, region: numpy.ndarray) -> None: ...
    def wait_for_debugger(host: str = "localhost", port: int = 5678) -> None: ...
    def write_message(message: str, show_message_box: bool = False) -> None: ...

Class ImageObjectIterator

Special Methods

__iter__()

Returns self.

Returns:

self: ecognition.ImageObjectIterator Returns self.

__next__()

Returns the next image object

Returns:

chunk: ecognition.ImageObject The image object.

Copy
class ImageObjectIterator:    
    def __iter__(self) -> ImageObjectIterator: ...    
    def __next__(self) -> ImageObject: ...

Class Feature

Methods

calculate()

Returns feature value for current scene.

Returns:

feature_value: int | float | str
The feature value.

calculate(obj: ImageObject)

Returns feature value for the Image Object.

Returns:

feature_value: int | float | str
The feature value.

get_min_range_value()

Returns minimum possible feature value.

Returns:

min_value: float
The minimum feature value.

get_max_range_value()

Returns maximum possible feature value.

Returns:

max_value: float
The maximum feature value.

Special Methods

__repr__()

Returns the string representation of the feature (unambigious).

Returns:

repr: str
String representation.

__str__()

Returns the string representation of the feature (easier to read).

Returns:

str: str
String representation.

Copy
class Feature:

    def _repr_(self) -> str: ...
    def _str_(self) -> str: ...
    def get_min_range_value() -> float: ...
    def get_max_range_value() -> float: ...

Functions

General Functions

set_array(name, values)

Fills an eCognition array with the given values. If an array does not exist, it is created. All elements of the values sequence must have the same type.

Parameters:

name: str
The name of the array.

values: sequence of int, float or str
The values to fill the array with.

Raises:

ValueError
If value type is unsupported. Or sequence elements are not of the same type.

set_region(name, region)

Sets an eCognition region. If a region does not exist, it is created. The region array must have a specific shape:

2D region

numpy.ndarray shape - [2, 2]

data - [[x_pos, y_pos], [x_size, y_size]]

3D region

numpy.ndarray shape - [2, 3]

data - [[x_pos, y_pos, z_pos], [x_size, y_size, z_size]]

4D region

numpy.ndarray shape - [2, 4]

data - [[x_pos, y_pos, z_pos, t_pos], [x_size, y_size, z_size, t_size]]

Time series region

numpy.ndarray shape - [2, 4]

data - [[x_pos, y_pos, 0, t_pos], [x_size, y_size, 0, t_size]]

(for time series region z_pos and z_size must be equal to 0)

x_pos, y_pos, z_pos, and t_pos are the starting points of a region.

x_size, y_size, z_size, and t_size define the extent of a region.

Parameters:

name: str The name of the region.

region: numpy.ndarray The numpy array containing region.

Raises:

ValueError If the region is of incorrect type or shape.

set_variable(name, value)

Sets an eCognition variable. If it does not exist, it is created.

Parameters:

name: str The name of the variable.

value: int, float or str The value to set the variable to.

Raises:

ValueError If value type is unsupported.

Utility Functions

wait_for_debugger(host=”localhost”, port=5678)

Blocks code execution and waits for a debugger to connect. Listens on a specified host and port. Debugger is implemented using a debugpy package: https://github.com/microsoft/debugpy, so it is possible to attach to the eCognition process and debug python code using tools that support debugpy.

Please refer to User Guide > Python Integration > Debugging python code in eCognition Developer for details.

Parameters:

host: str The host to listen for the debugger on.

port: int The port to listen for the debugger on.

Raises:

ValueError If the host or port has been changed after the debug session has already been created.

RuntimeError
If this function is called on Linux (only Windows is supported).
If debugpy package is not installed in the active environment.

write_message(message, show_message_box=False)

Writes a message to the eCognition log file. It also shows up in the View -> Message Console window. If show_message_box is True, then in addition, an information window box shows up with the message. Script execution is blocked until the message box is closed.

Parameters:

message: str The message to write.

show_message_box: bool Whether to show a message box.

Hints

Hint 1 - Printing from python script

Because the console window is disabled in eCognition Developer, Pythons standard output to stdout is not visible. This hint lists some alternatives, in case you need to print some debug information during the development of your script.

The simplest way to print a message from python is to use a ecognition.write_message function:

 

Copy
import ecognition as ecog

def print_message(input_dict):  
    print_string = "Use write_message function"  
    ecog.write_message(print_string, True)

 

Another way to print debug messages would be to use an external log file (a dedicated logging package is recommended for this approach). For example:

Copy
def log_to_file(input_dict):  
    log_file = input_dict["variable"]["var_log_file"]  
    
    with open(log_file, "a") as file: 
          file.write("log entry 1\n")    
        file.write("log entry 2\n")


Hint 2 - Using external python files in inline script

If you need to import an external file into a python script, the script must be enabled to find that external file. That is done by adding the location of the external file into the process parameter “External script paths”. For example, for the following script: C:\scripts\ExternalFile.py

Copy
import ecognition as ecog

def set_variable():  
    ecog.set_variable("var_from_ext_file", "Set from external file.")

 

And this inline python script:

Copy
from ExternalFile 
    import set_variable
    def use_external_file(input_dict):  
        set_variable()

It is important to define the parameter “External scripts path” as an array that contains “C:\scripts” as string value.

 

For more information see also:

Installation Guide > Windows > Python Installation - installation and setup

Reference Book > Algorithms and Processes > Miscellaneous > Python Script - description algorithm and its parameters

Reference Book > Algorithms and Processes > Miscellaneous > Embedded Python API Reference - reference for each class, properties and methods

User Guide > Python Integration - application examples for python scripts and Debugging python code in eCognition Developer